const NFs = require('fs');


var readFs = {
  // 读取索引列表
  indexList () {
    let path = __dirname + '/database/data/index/';
    return new Promise((resolve, reject) => {
      NFs.readdir(path, function (err, files) {
        if (err) {
          resolve();
          return console.log('文件夹读取失败：' + path);
        }
        resolve(
          files.map(item => {
            return path + item;
          })
        )
      })
    })
  },

  // 根据名称与条件读取索引详情
  indexDetail (filepath, aType) {
    return new Promise((resolve, reject) => {
      NFs.readFile(filepath, function (err, data) {
        if (err) {
          reject();
          return console.log(`文件读取失败：${filepath}`);
        }
        data = data.toString().split('\n');
        for (let i = 0; i < data.length; i++) {
          let aItem = data[i];
          // 用length<10来判断是否是最后一行，最后一行是空，
          if (aItem.length < 10) {
            continue;
          }
          let obj = JSON.parse(aItem);
          obj.b.forEach(item => {
            if (aType.indexOf(item) == -1) {
              aType.push(item);
            }
          })
        }
        resolve();
      })
    })
  }
}


getType();

async function getType () {
  let filepaths = await readFs.indexList();
  let aType = [];
  for (let i = 0; i < filepaths.length; i++) {
    await readFs.indexDetail(filepaths[i], aType);
  }
  aType.sort();

  NFs.writeFile('type.json', JSON.stringify(aType), function(err) {
    if(err) {
      console.log('报错了')
    }
  });
}















